<?php
/**
 * Created by PhpStorm.
 * User: HeiYanHeiMao
 * Date: 2020/4/6
 * Time: 23:11
 */

namespace app\back\model;

use Exception;
use think\facade\Db;
use think\response\Json;

class MenuModel
{
    private static $_table = 'menu'; // 菜单表
    private static $_roleTable = 'role'; // 角色表

    /**获取权限列表
     * @return Json
     */
    public static function getAuthList()
    {
        try {
            $list = Db::table(self::$_table)->field('id,pid,name,level')->order('sort','asc')->select()->toArray();
            if ($list) {
                return jsonSuccess('获取成功', getTree($list));
            } else {
                return jsonSuccess('暂无数据',[]);
            }
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**获取单个权限
     * @param $input
     * @return Json
     */
    public static function getAuthOnly($input)
    {
        try {
            $menuInfo = Db::table(self::$_table)->field('*')->where('id', $input['id'])->find();
            if (!$input) return jsonFail('未找到数据');
            return jsonSuccess('获取成功', $menuInfo);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**编辑权限
     * @param $input
     * @return Json
     */
    public static function editAuth($input)
    {
        try {
            $update = [
                'name' => $input['name'],
                'sort' => $input['sort']
            ];
            $map[] = ['id', '=', $input['id']];
            switch ($input['level']) {
                case 0;
                    $update['icon'] = $input['icon'];
                    break;
                case 1;
                    $update['router'] = $input['router'];
                    $update['component'] = $input['component'];
                    break;
                case 2;
                    $update['api'] = $input['api'];
                    break;
                default:
                    return jsonFail('不正确的level');
            }
            $rtn = Db::table(self::$_table)->where($map)->update($update);
            if ($rtn == 0) return jsonFail('数据未发生更改，更新失败');
            return jsonSuccess('编辑成功');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**添加权限
     * @param $input
     * @return Json
     */
    public static function addAuth($input)
    {
        $flag = false;
        try {
            $insert = [
                'name' => $input['name'],
                'pid' => $input['pid'],
                'level' => $input['level'] + 1,
                'create_time' => time(),
                'sort' => $input['sort']
            ];
            switch ($input['level']) {
                case -1;
                    $insert['icon'] = $input['icon'];
                    break;
                case 0;
                    $insert['router'] = $input['router'];
                    $insert['component'] = $input['component'];
                    break;
                case 1;
                    $insert['api'] = $input['api'];
                    break;
                default:
                    return jsonFail('不可能的level');
            }
            Db::startTrans();
            $flag = true;
            $id = Db::table(self::$_table)->insertGetId($insert);
            if ($id < 1) {
                Db::rollback();
                return jsonFail('添加失败');
            }

            $update['menu_ids'] = Db::raw("CONCAT(`menu_ids`, '{$id},')");
//            if ($input['is_show'] == 1) {
//                if ($input['level'] == 1) {
//                    $update['left_auth_ids'] = Db::raw("CONCAT(`left_auth_ids`, '{$id},')");
//                } else {
//                    $update['left_menu_ids'] = Db::raw("CONCAT(`left_menu_ids`, '{$id},')");
//                }
//            }
            $rtn = Db::table(self::$_roleTable)->where('id', 1)->update($update);
            if (!$rtn) {
                Db::rollback();
                return jsonFail('添加失败');
            }
            Db::commit();
            return jsonSuccess('添加成功');
        } catch (Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**删除权限
     * @param $input
     * @return Json
     */
    public static function delAuth($input)
    {
        $flag = false;
        try {
            $table = self::$_table;
            Db::startTrans();
            $flag = true;
            $map = "id = {$input['id']} and not exists (select id from (select id from {$table} where pid = {$input['id']}) t)";
            $rtn = Db::table(self::$_table)->whereRaw($map)->delete();
            if ($rtn == 1) {
                $rtn = Db::table(self::$_roleTable)->where('1 = 1')->update([
                    'menu_ids' => Db::raw("replace(menu_ids, ',{$input['id']},', ',')"),
                    'left_menu_ids' => Db::raw("replace(left_menu_ids, ',{$input['id']},', ',')"),
                ]);
                if ($rtn) {
                    Db::commit();
                    return jsonSuccess('删除成功');
                }
            }
            Db::rollback();
            return jsonFail('存在下级权限或未找到数据，删除失败');
        } catch (Exception $e) {
            if ($flag == true) Db::rollback();
            return jsonFail('服务内部错误~');
        }
    }

    /**获取当前管理员权限
     * @param $input
     * @return Json
     */
    public static function getAdminAuth($info)
    {
        $rtn = self::getAdminAuthStatic($info);
        if (is_array($rtn)) return jsonSuccess('获取成功', $rtn);
        return $rtn;
    }

    /**获取当前管理员权限
     * @param $info
     * @return array|Json
     */
    public static function getAdminAuthStatic($info)
    {
        try {
            $field = 'id,pid,name';
            if ($info['role_id'] == 1) {
                // 超管
                $map = [];
            } else {
                // 其他管理员
                $map[] = ['id', 'in', $info['menu_ids']];
            }
            $list = Db::table(self::$_table)->field($field)->where($map)->select()->toArray();
            if ($list) return getTree($list);
            return jsonFail('请先添加权限');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**获取超管获取左侧列表
     * @param $info
     * @return Json
     */
    public static function getMenuList($info)
    {
        try {
            $menuList = Db::table(self::$_table)->field('id,pid,name,level')->order('sort','asc')->select()->toArray();
            // 获取三级权限
            $checkIds = Db::table(self::$_table)->where('level', 2)->field('id')->where('id', 'in', $info['left_menu_ids'])->select()->toArray();
            return jsonSuccess('获取成功', ['menu_list' => getTree($menuList), 'checked_list' => array_column($checkIds, 'id')]);
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }

    /**编辑超管左侧菜单
     * @param $input
     * @return Json
     */
    public static function editMenu($input)
    {
        try {
            $map[] = ['id', '=', 1];
            $input['left_menu_ids'] = ',' . $input['left_menu_ids'] . ',';
            $rtn = Db::table(self::$_roleTable)->where($map)->update($input);
            if ($rtn == 0) return jsonFail('数据未发生更改，更新失败');
            return jsonSuccess('编辑成功');
        } catch (Exception $e) {
            return jsonFail('服务内部错误~');
        }
    }
}